<template>
  <el-dialog v-model="visible" :width="'30%'" :title="!dataForm.id ? '新增' : '修改'" :close-on-click-modal="false"
             :close-on-press-escape="false">
    <el-form :model="dataForm" :rules="rules" ref="dataFormRef" @keyup.enter="dataFormSubmitHandle()"
             label-width="120px">
      <el-form-item label="用户账号" prop="mobile">
        <el-input v-model="dataForm.mobile" placeholder="用户账号"></el-input>
      </el-form-item>
      <el-form-item label="用户呢称" prop="username">
        <el-input v-model="dataForm.username" placeholder="用户呢称"></el-input>
      </el-form-item>
      <el-form-item label="用户头像" prop="url">
        <el-upload
          class="avatar-uploader"
          :action="url"
          :show-file-list="false"
          :on-success="successHandle"
          :before-upload="beforeUploadHandle">
          <img v-if="dataForm.url" :src="dataForm.url" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item label="用户角色" prop="userrole">
        <el-select v-model="dataForm.userrole"  placeholder="用户角色">
          <el-option
            v-for="item in dataForm.userroleOp"
            :key="item"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="用户状态" prop="userstate">
        <el-select v-model="dataForm.userstate"  placeholder="用户状态">
          <el-option
          v-for="item in dataForm.userstateOp"
          :key="item.value"
          :label="item.label"
          :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="登陆密码" prop="password">
        <el-input v-model="dataForm.password"  type="password" placeholder="登陆密码" :class="{'is-required': !dataForm.id }"></el-input>
      </el-form-item>
      <el-form-item prop="confirmPassword" label="确认密码" :class="{ 'is-required': !dataForm.id }">
        <el-input v-model="dataForm.confirmPassword" type="password" placeholder="确认密码"></el-input>
      </el-form-item>
    </el-form>
    <template v-slot:footer>
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmitHandle()">确定</el-button>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import {reactive, ref} from "vue";
import baseService from "@/service/baseService";
import {ElMessage} from "element-plus";
import app from "@/constants/app";
import {getToken} from "@/utils/cache";
import {IObject} from "@/types/interface";

const emit = defineEmits(["refreshDataList"]);

const visible = ref(false);
const dataFormRef = ref();

const dataForm = reactive({
  id: '', username: '', mobile: '', password: '', userrole: '', userprojectid: '', userstate: '', createDate: '',url:"",
  userroleOp:[{label:"施工人员", value:1},{label:"施工负责人" ,value:2},{label:"管理人员" ,value:3}],
  userstateOp:[{label:"启用", value:1},{label:"禁用" ,value:2}]
});


const validatePassword = (rule: any, value: string, callback: (e?: Error) => any): any => {
  if (!dataForm.id && !/\S/.test(value)) {
    return callback(new Error("登陆密码不能为空"));
  }
  callback();
};
const validateConfirmPassword = (rule: any, value: string, callback: (e?: Error) => any): any => {
  if (!dataForm.id && !/\S/.test(value)) {
    return callback(new Error("确认密码不能为空"));
  }
  if(""!=dataForm.password && undefined !=dataForm.password){
    if (dataForm.password !== value) {
      return callback(new Error("确认密码与密码输入不一致"));
    }
  }
  callback();
};
const rules = ref({
  username: [{required: true, message: '用户名呢称不能为空', trigger: 'blur'}],
  mobile: [{required: true, message: '用户账号不能为空', trigger: 'blur'}],
  password: [{validator: validatePassword, trigger: 'blur'}],
  confirmPassword: [{ validator: validateConfirmPassword, trigger: "blur" }],
  userrole: [{required: true, message: '管理员状态不能为空', trigger: 'blur'}],
  userstate: [{required: true, message: '用户状态不能为空', trigger: 'blur'}],
});
const url = ref("");
const fileUrl = ref("");
const init = (row: {}) => {
  visible.value = true;
  dataForm.id = "";
  // 重置表单数据
  if (dataFormRef.value) {
    dataFormRef.value.resetFields();
  }
  debugger
  if(Object.keys(row).length>0){
    Object.assign(dataForm,row);
  }else{
    Object.assign(dataForm,row);
    dataForm.userstate =1
  }
  dataForm.password = "";
  url.value = `${app.api}/sys/oss/uploadByLocal?token=${getToken()}`;
  fileList.value =[]
  fileUrl.value = `${app.api}/sys/oss/downloadLocal`;
};

// 获取信息
const getInfo = (id: number) => {
  baseService.get("/sysapp/user/" + id).then((res) => {
    Object.assign(dataForm, res.data);
  });
};

// 表单提交
const dataFormSubmitHandle = () => {
  dataFormRef.value.validate((valid: boolean) => {
    if (!valid) {
      return false;
    }
    (!dataForm.id ? baseService.post : baseService.put)("/sysapp/user", dataForm).then((res) => {
      ElMessage.success({
        message: '成功',
        duration: 500,
        onClose: () => {
          visible.value = false;
          emit("refreshDataList");
        }
      });
    });
  });
};

defineExpose({
  init
});

const fileList = ref<IObject[]>();
const num =  ref(0);
// 上传之前
const beforeUploadHandle = (file: IObject) => {
  if (file.type !== "image/jpg" && file.type !== "image/jpeg" && file.type !== "image/png" && file.type !== "image/gif") {
    ElMessage.error("只支持jpg、png、gif格式文件！");
    return false;
  }
  num.value++;
};

// 上传成功
const successHandle = (res: IObject, file: IObject, list: IObject[]) => {
  if (res.code !== 0) {
    return ElMessage.error(res.msg);
  }
  ElMessage.success({
    message: "文件上传成功",
    duration: 500,
    onClose: () => {
      let url =fileUrl.value+"?name="+res.data.url;
      dataForm.url=url;
    }
  });
};
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}
.avatar {
  width: 100px;
  height: 100px;
  display: block;
}
</style>
